package com.hunttown.mes.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;

/**
 * created by hunttown on 2017/7/26
 */
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getContext() {
        checkApplicationContext();
        return applicationContext;
    }


    public static <T> T getBeanByName(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }


    public static <T> T getBeanByType(Class<T> clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }

    private static void checkApplicationContext() {
        Assert.notNull(applicationContext, "applicaitonContext未注入, 请在applicationContext.xml中定义SpringContextUtil");
    }
}
